import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import 'sputil.dart';

class AddressBookModel {
  final String Friendusername;
  final String Friendname;

  final bool Online;

  AddressBookModel(
      {required this.Friendusername,
      required this.Friendname,
      required this.Online});

  factory AddressBookModel.fromJson(Map<String, dynamic> json) {
    return AddressBookModel(
        Friendusername: json["Friendusername"],
        Friendname: json["Friendname"],
        Online: json["Online"]);
  }

  factory AddressBookModel.empty() {
    return AddressBookModel(Friendusername: '', Friendname: '', Online: false);
  }
}

Future<List<AddressBookModel>> api_addressbook(context) async {
  List<AddressBookModel> result = List<AddressBookModel>.empty();

  var spu = SpUtil();

  var authorization = "Bearer ${spu.get<String>("token")}";

  try {
    final response = await http.get(
        Uri.parse('https://rtc.jxt.elef.top:8086/user/addressbook'),
        headers: <String, String>{
          'Content-Type': 'application/json; charset=UTF-8',
          "Authorization": authorization
        });

    print(response.statusCode);

    if (response.statusCode == 200) {
      //print(response.body);

      final List decodedJson =
          json.decode(new Utf8Decoder().convert(response.bodyBytes));
      result = decodedJson.map((e) => AddressBookModel.fromJson(e)).toList();
    } else {}
  } catch (e) {
    print(e);
  }
  return result;
}

class AddressBookProvider with ChangeNotifier {
  List<AddressBookModel> addressbooks = List<AddressBookModel>.empty();
  bool loading = false;

  Load(context) async {
    loading = true;
    addressbooks = await api_addressbook(context);
    loading = false;

    return addressbooks;
  }
}
